package com.study.heartBeat;

import com.study.handler.NettyClientHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.ServerSocketChannel;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.Random;
import java.util.Scanner;

/**
 * @ClassName: NettyHeartBeatClient
 * @Description:
 * @Date 2024/04/30 11:12
 * @Author songshaoqiu
 **/
public class NettyHeartBeatClient {
    public static void main(String[] args) {
        NioEventLoopGroup eventExecutors = new NioEventLoopGroup();
        try {
            //创建客户端启动对象
            Bootstrap bootstrap = new Bootstrap();
            //设置相关参数
            bootstrap.group(eventExecutors)
                    //使用NioSocketChannel作为客户端的通道实现
                    .channel(NioSocketChannel.class)
                    //创建通道初始化对象并设置handler业务处理器
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast(new StringDecoder());
                            socketChannel.pipeline().addLast(new StringEncoder());
                            //添加处理器。 处理器里面是实现具体业务的
                            socketChannel.pipeline().addLast(new NettyHeartBeatClientHandler());
                        }
                    });
            System.out.println("客户端启动了");
            //同步阻塞的告知客户端连接的服务器地址，并启动客户端
            ChannelFuture connect = bootstrap.connect("127.0.0.1", 9090);
            connect.sync();
            Scanner scanner =new Scanner(System.in);
            while (scanner.hasNextLine()){
                String msx = scanner.nextLine();
                //发送消息到channel
                connect.channel().writeAndFlush(msx);
            }
            //阻塞等待完成操作后 关闭通道
            //模拟向服务器 端发送心跳数据
            String packet ="heartbeat packet";
            //阻塞等待完成操作后 关闭通道
            // connect.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }finally {
            eventExecutors.shutdownGracefully();
        }
    }
}
